// 设备检测组合函数 - 基于优秀项目实践
import { ref, computed, onMounted, onUnmounted } from 'vue'

/**
 * 设备类型检测组合函数
 */
export function useDevice() {
  // 响应式状态
  const windowWidth = ref(window.innerWidth)
  const windowHeight = ref(window.innerHeight)
  
  // 断点配置 (基于主流项目的断点设置)
  const breakpoints = {
    xs: 480,
    sm: 640, 
    md: 768,
    lg: 1024,
    xl: 1280,
    '2xl': 1536
  }
  
  // 计算属性
  const isMobile = computed(() => windowWidth.value < breakpoints.md)
  const isTablet = computed(() => 
    windowWidth.value >= breakpoints.md && windowWidth.value < breakpoints.lg
  )
  const isDesktop = computed(() => windowWidth.value >= breakpoints.lg)
  
  const screenType = computed(() => {
    if (isMobile.value) return 'mobile'
    if (isTablet.value) return 'tablet'
    return 'desktop'
  })
  
  // 事件处理
  const updateSize = () => {
    windowWidth.value = window.innerWidth
    windowHeight.value = window.innerHeight
  }
  
  // 防抖处理
  let resizeTimer = null
  const handleResize = () => {
    if (resizeTimer) {
      clearTimeout(resizeTimer)
    }
    resizeTimer = setTimeout(updateSize, 100)
  }
  
  // 生命周期
  onMounted(() => {
    window.addEventListener('resize', handleResize)
    updateSize() // 初始化尺寸
  })
  
  onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
    if (resizeTimer) {
      clearTimeout(resizeTimer)
    }
  })
  
  return {
    windowWidth,
    windowHeight,
    isMobile,
    isTablet,
    isDesktop,
    screenType,
    breakpoints,
    updateSize
  }
}